package com.example.rabc.controller;

import com.example.rabc.common.ApiResponse;
import com.example.rabc.service.RealOAuthService;
import com.example.rabc.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * OAuth2控制器，处理OAuth2回调
 */
@RestController
public class OAuth2Controller {

    private static final Logger logger = LoggerFactory.getLogger(OAuth2Controller.class);

    @Autowired
    private RealOAuthService realOAuthService;

    @Autowired
    private UserService userService;

    /**
     * OAuth2登录成功后的回调端点
     * @return 认证结果
     */
    @GetMapping("/oauth2/success")
    public ApiResponse<?> oauth2Success() {
        try {
            logger.info("Processing OAuth2 success callback");

            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (!(authentication instanceof OAuth2AuthenticationToken)) {
                logger.warn("Current authentication is not OAuth2: {}", authentication);
                return ApiResponse.error("Not authenticated with OAuth2");
            }

            OAuth2AuthenticationToken oauth2Token = (OAuth2AuthenticationToken) authentication;

            // 验证令牌并获取用户信息
            OAuth2User oauth2User = realOAuthService.validateAndGetUser(oauth2Token);

            if (oauth2User == null) {
                return ApiResponse.error("Failed to validate OAuth2 token");
            }

            String username = oauth2User.getName();
            logger.info("Authenticated user: {}", username);

            // 同步用户角色（从外部服务）
            boolean syncResult = userService.syncUserRolesFromExternalService(username);
            logger.info("Role sync result for user {}: {}", username, syncResult);

            // 返回成功响应
            return ApiResponse.success("Authentication successful for user: " + username);
        } catch (Exception e) {
            logger.error("Error processing OAuth2 success callback", e);
            return ApiResponse.error("Authentication failed: " + e.getMessage());
        }
    }

    /**
     * OAuth2登录失败的回调端点
     * @return 失败结果
     */
    @GetMapping("/oauth2/failure")
    public ApiResponse<?> oauth2Failure() {
        logger.warn("OAuth2 authentication failed");
        return ApiResponse.error("OAuth2 authentication failed");
    }
}